package com.axend.aerosense.login.utils;

import android.app.Activity;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.common.bean.TipsBean;
import com.axend.aerosense.common.bean.UpdataPasswordBean;
import com.axend.aerosense.common.bean.VerificationBean;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.login.bean.LoginBean;
import com.axend.aerosense.login.bean.LoginResultBean;
import com.axend.aerosense.login.bean.RegisterBean;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.app.BaseApplication;
import com.axend.aerosense.base.bean.BaseDevInfoBean;
import com.axend.aerosense.base.bean.RoomTypeBean;
import com.axend.aerosense.base.database.room.RoomTypeMananger;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.base.impl.ISimpleAction;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.RoomTypeInfoBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.CheckUtil;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.login.R;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.exception.ApiException;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * 登录注册工具
 */
public class LoginRegistUtil {

    private static class SingletonHolder{
        private static LoginRegistUtil instance = new LoginRegistUtil();
    }

    public static LoginRegistUtil getInstance() {
        return SingletonHolder.instance;
    }
    /**
     * 注册接口
     * @param activity
     * @param email
     * @param password
     * @param vcode
     * @param operationResult
     */
    public Disposable onRegister(final Activity activity, String email, String password, String vcode, ISimpleAction<LoginResultBean> operationResult){
        if(!CheckUtil.isEmail(email) ){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_email));
            }
            return null;
        }
        if(!CheckUtil.isPasswordOk(password)){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_password));
            }
            return null;
        }
        if(!CheckUtil.isVcodeOk(vcode)){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_vcode));
            }
            return null;
        }
        RegisterBean bean = new RegisterBean(email, password, vcode);
        return EasyHttp.post(UrlApi.URL.Register.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<LoginResultBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        //登录界面不做处理
                        dismissProgress();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail(e.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(LoginResultBean bean) {
                        dismissProgress();
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.TOKEN, bean.getToken());
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LOGIN_EMAIL, email);
                        if(null != operationResult){
                            operationResult.onSuccess(bean);
                        }
                    }
                });
    }

    /**
     * 登录接口
     * @param activity
     * @param email
     * @param password
     * @param operationResult
     */
    public Disposable onLogin(final Activity activity, String email, String password, ISimpleAction<LoginResultBean> operationResult){
        if(!CheckUtil.isEmail(email) ){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_email));
            }
            return null;
        }
        if(!CheckUtil.isPasswordOk(password)){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_password));
            }
            return null;
        }
        LoginBean bean = new LoginBean(email, password);
        return EasyHttp.post(UrlApi.URL.PwdLogin.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<LoginResultBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        //登录界面不做处理
                        dismissProgress();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        if(null != operationResult){
                            operationResult.onFail(e.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(LoginResultBean bean) {
                        dismissProgress();
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.TOKEN, bean.getToken());
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LOGIN_EMAIL, email);
                        if(null != operationResult){
                            operationResult.onSuccess(bean);
                        }
                    }
                });
    }

    /**
     * 登录后完成房间类型数据的拉取
     * @param activity
     * @param token
     * @param callback
     */
    public Disposable getRoomType(Activity activity, String token, IComplete callback){
        return EasyHttp.post(UrlApi.URL.GetRoomType.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.FIRSTREMOTE)
                .cacheKey("room_type")
                .cacheTime(-1)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new ProgressDialogCallBack<RoomTypeInfoBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        //登录界面不做处理
                        dismissProgress();
                        if(null != callback){
                            callback.complete();
                        }
                    }

                    @Override
                    public void onError(ApiException e){
                        dismissProgress();
                        if(null != callback){
                            callback.complete();
                        }
                    }

                    @Override
                    public void onSuccess(RoomTypeInfoBean bean) {
                        dismissProgress();
                        if(null != bean.getRoomInfo() && bean.getRoomInfo().size() > 0){
                            ArrayList<RoomTypeBean> list = BaseApplication.getInstance().getRoomTypes();
                            list.clear();
                            list.addAll(bean.getRoomInfo());
                            RoomTypeMananger.getInstance(activity.getApplicationContext()).roomDao().insertList(list);
                        }

                        if(null != callback){
                            callback.complete();
                        }
                    }
                });
    }

    /**
     * 获取邮件验证码
     * @param userEmail
     * @param actionType
     * @param operationResult
     */
    public Disposable getEmailVCode(Activity activity, String userEmail, VerificationBean.ActionType actionType, IOperationResult operationResult){
        if(!CheckUtil.isEmail(userEmail) ){
            ToastUtils.showShort(R.string.common_check_email);
            return null;
        }
        VerificationBean bean = new VerificationBean(userEmail, actionType.getValue());
        return EasyHttp.post(UrlApi.URL.Verification.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)){
                    @Override
                    public void onTokenExpire() {
                        //登录界面不做处理
                        dismissProgress();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        if(!TextUtils.isEmpty(e.getMessage())){
                            ToastUtils.showShort(e.getMessage());
                        }else{
                            ToastUtils.showShort(R.string.common_fail);
                        }
                        if(null !=operationResult){
                            operationResult.onFail();
                        }

                    }

                    @Override
                    public void onSuccess(BaseStringBean s) {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_success);
                        if(null !=operationResult){
                            operationResult.onSuccess();
                        }
                    }
                });
    }

    /**
     *  修改密码
     * @param activity
     */
    public Disposable onUpdataPassword(final Activity activity, String email, String password, String vcode, ISimpleAction<String> operationResult){
        if(!CheckUtil.isEmail(email) ){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_email));
            }
            return null;
        }
        if(!CheckUtil.isPasswordOk(password)){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_password));
            }
            return null;
        }
        if(!CheckUtil.isVcodeOk(vcode)){
            if(null != operationResult){
                operationResult.onFail(activity.getString(R.string.common_check_vcode));
            }
            return null;
        }
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        UpdataPasswordBean bean = new UpdataPasswordBean(email, password, vcode);
        return EasyHttp.post(UrlApi.URL.UpdataPassword.getUrl())
                .headers("token", token)
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(bean))
                .execute(new ProgressDialogCallBack<TipsBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        dismissProgress();
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        ToastUtils.showShort(e.getMessage());
                        if(null != operationResult){
                            operationResult.onFail(e.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(TipsBean bean) {
                        ToastUtils.showShort(R.string.common_success);
                        dismissProgress();
                        if(null != operationResult){
                            operationResult.onSuccess(null);
                        }
                    }
                });
    }
}
